#include <iostream>
#include "LinkTree.h"
#include <cstring>
#include <dirent.h>
void showString(void* element)
{
    std::cout<<(char*)element<<std::endl;
}

bool IsStringEqual(void *p1,void *p2)
{
    return strcmp((char*)p1,(char*)p2) == 0;
}

void ExploreDirectory(const std::string& path,Node*node)
{   
    //文件夹结构体
    //打开文件夹
    DIR *dir = opendir(path.c_str());
    if(dir == nullptr)
    {   
        std::cout<<"文件夹路径有问题!\n";
        return;
    }
    struct dirent *e = nullptr;
    //读取文件夹下的文件内容
    while((e = readdir(dir)) != nullptr)
    {   
        if(strcmp(e->d_name,".") == 0 || strcmp(e->d_name,"..") == 0)
        {
            continue;
        }
        Node *fileNode = new Node(strdup (e->d_name));
        fileNode->Connect(node);

        if(e->d_type == 4)
        {
            ExploreDirectory(path + "/" + std::string(e->d_name),fileNode);
        }
        // std::cout<<e->d_name<<" "<<(int)e->d_type<<std::endl;
    }
    //关闭文件夹
    closedir(dir);
}
int main(int argc,char *argv[])
{   
    std::string path = argc < 2 ? "./" : argv[1];
    LinkTree tree;
   
    // Node *class1 = new Node((void*)"259班");
    // Node *class2 = new Node((void*)"262班");

    // class1->Connect(tree.GetRoot());
    // class2->Connect(tree.GetRoot());

    // Node *stu1 = new Node((void*)"zhangsan");
    // Node *stu2 = new Node((void*)"lisi");
    // Node *stu3 = new Node((void*)"wangwu");

    // stu1->Connect(class1);
    // stu2->Connect(class1);
    // stu3->Connect(class2);

    // tree.SetShowtype(showString);
    // // tree.show();

    // tree.SetFindType(IsStringEqual);
    // Node *n = tree.FindNode((void*)"lisi");
    // if(n)
    // {
    //     n->DisConnect();
    // }
    // n->Connect(tree.FindNode((void*)"262班"));
    
    // tree.show();
    Node *rootNode = new Node(strdup(path.c_str()));
    rootNode->Connect(tree.GetRoot());
    ExploreDirectory(path,rootNode);
    tree.SetShowtype(showString);
    tree.show();

    std::string FileName;
    std::cin>>FileName;
    tree.SetFindType(IsStringEqual);
    Node *target = tree.FindNode((void*)FileName.c_str());
    std::string pwd;
    while(target->GetParent() != nullptr)
    {
        pwd = std::string((char*)target->GetData()) + "/" + pwd;
        target = target->GetParent();
    }
    pwd.erase(pwd.size()-1);
    std::cout<<pwd<<std::endl;
    return 0;

}